package com.inforich.area.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inforich.area.domain.Area;
import com.inforich.area.mapper.AreaMapper;
import com.inforich.area.service.IAreaService;
import com.inforich.common.core.domain.TreeSelect;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * 地区Service业务层处理
 *
 * @author hjm
 * @date 2022-10-23
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements IAreaService {

  @Override
  public Page<Area> pageArea(Page<Area> page, Map<String, Object> map) {
    return baseMapper.pageArea(page, map);
  }

  @Override
  public List<Area> listArea(Map<String, Object> map) {
    return baseMapper.listArea(map);
  }

  @Override
  public List<TreeSelect> selectAreaTreeList(List<Area> parentList, List<Area> list) {
    // 父节点树
    List<TreeSelect> tree = convert(parentList);
    // 根据父类型分组
    Map<String, List<Area>> map = list.stream()
        .filter(b -> b.getParentId() != null)
        .collect(Collectors.groupingBy(Area::getParentId));
    recursionFn(tree, map);
    return tree;
  }

  /**
   * 对象->树对象
   */
  private List<TreeSelect> convert(List<Area> list) {
    return list.stream().map(l -> {
      TreeSelect t = new TreeSelect();
      t.setId(Long.valueOf(l.getId()));
      t.setLabel(l.getName());
      return t;
    }).collect(Collectors.toList());
  }

  /**
   * 递归列表
   */
  private void recursionFn(List<TreeSelect> tree, Map<String, List<Area>> map) {
    tree.forEach(t -> {
      List<Area> children = map.get(String.valueOf(t.getId()));
      if (CollUtil.isNotEmpty(children)) {
        List<TreeSelect> treeChildren = convert(children);
        t.setChildren(treeChildren);
        recursionFn(treeChildren, map);
      }
    });
  }

}
